package com.lethelh.jdbc.sample;

import com.lethelh.jdbc.utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * jdbc事务Demo
 * @author jasonper
 */
public class TransactionDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement stmt = null;
        try {
            conn = DBUtils.getConnection();
            conn.setAutoCommit(false);// 设置手动事务
            for (int i = 7; i < 1000; i++) {
                String sql = "insert into goods (name,price,desp) VALUES (?,?,?);";
                stmt = conn.prepareStatement(sql);
                stmt.setString(1,"商品"+i);
                stmt.setFloat(2,5000);
                stmt.setString(3,"商品"+i+"的描述");
                stmt.executeUpdate();
            }
            conn.commit();// 事务提交
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            try {
                conn.rollback();// 遇到错误，事务回滚
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();// 遇到错误，事务回滚
            }
        }finally {
            try {
                DBUtils.closeConnection(null, stmt, conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
